<!-- src/views/Home.vue -->
<template>
  <div class="app" style="min-height: 100vh; background: linear-gradient(to bottom right, #2E2D2D, #1C1C1C)">
    <div class="container">
      <!-- Logo -->
      <div class="logo">
        <h2 class="title">AI 音乐</h2>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <h3 class="label">歌曲描述</h3>
        <textarea v-model="desc" placeholder="请输入歌曲提示词" rows="3" class="input"></textarea>

        <div class="options">
          <label>
            <input type="checkbox" v-model="instrumental" />
            纯音乐
          </label>
          <select v-model="model" class="select">
            <option value="chirp-v3-5">v3.5</option>
            <option value="chirp-v2-xxl-alpha">v2.0</option>
          </select>
        </div>

        <button
          :disabled="isLoading"
          class="button"
          @click="handleGenerate"
        >
          <span v-if="isLoading">{{ genStates }}</span>
          <span v-else>生成</span>
        </button>
      </div>

      <!-- 历史记录 -->
      <div class="history">
        <h3 class="label">历史记录</h3>
        <div class="list">
          <div
            v-for="song in listInfo"
            :key="song.id"
            class="list-item"
            @click="selectSong(song)"
          >
            <img :src="song.image_url || fallbackCover" alt="cover" class="cover" />
            <div class="details">
              <h4 :class="{ active: song.id === playingIndex }">{{ song.title }}</h4>
              <p>{{ song.meta_data?.tags }}</p>
            </div>
            <button class="download-btn" @click.stop="downloadSong(song.audio_url, song.title)">
              下载
            </button>
          </div>
        </div>
      </div>

      <!-- 清空历史记录 -->
      <button class="clear-button" @click="clearList">清空历史记录</button>

      <!-- 歌词 -->
      <textarea
        v-model="audioLyrics"
        disabled
        placeholder="选择歌曲来显示歌词"
        rows="6"
        class="lyrics"
      ></textarea>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from "vue";
import { useToast } from "vue-toastification";
import localforage from "localforage";
import axios from "axios";
import MusicService from "@/services/MusicService";

export default {
  setup() {
    const toast = useToast();

    // 状态
    const desc = ref("");
    const instrumental = ref(false);
    const model = ref("chirp-v3-5");
    const isLoading = ref(false);
    const genStates = ref("完成");
    const audioSource = ref("https://cdn1.suno.ai/silence.mp3");
    const audioLyrics = ref("");
    const playingIndex = ref("");
    const list = ref([]);
    const listInfo = ref([]);
    const fallbackCover = ref("fallbackCover.png");
    const audioRef = ref(null);

    // 初始化本地存储
    const initList = async () => {
      try {
        const storedList = await localforage.getItem("List");
        if (storedList && storedList.length !== 0) {
          list.value = storedList;
        } else {
          await localforage.setItem("List", list.value);
        }
      } catch (err) {
        console.error("Error initializing list:", err);
      }
    };

    const queryList = async () => {
      if (list.value.length === 0) return;
      try {
        const response = await MusicService.query(list.value);
        listInfo.value = response;
      } catch (err) {
        console.error("Error querying list:", err);
      }
    };

    const clearList = async () => {
      try {
        await localforage.clear();
        list.value = [];
        listInfo.value = [];
      } catch (err) {
        console.error("Error clearing list:", err);
      }
    };

    const handleGenerate = async () => {
      if (!desc.value) {
        toast.error("请输入歌曲描述！");
        return;
      }
      isLoading.value = true;
      genStates.value = "正在生成";
      try {
        const response = await MusicService.generate(desc.value, instrumental.value, model.value);
        list.value.unshift(response.id);
        await localforage.setItem("List", list.value);
        queryList();
        genStates.value = "完成";
      } catch (err) {
        console.error("Error generating music:", err);
        toast.error("生成任务失败，请重试！");
      } finally {
        isLoading.value = false;
      }
    };

    const selectSong = (song) => {
      playingIndex.value = song.id;
      audioSource.value = song.audio_url;
      audioLyrics.value = song.meta_data?.prompt || "";
      const audio = audioRef.value;
      if (audio) {
        audio.src = audioSource.value;
        audio.play();
      }
    };

    const downloadSong = (url, title) => {
      axios.get(url, { responseType: "blob" }).then((res) => {
        const blobUrl = URL.createObjectURL(new Blob([res.data], { type: "audio/mpeg" }));
        const a = document.createElement("a");
        a.href = blobUrl;
        a.download = `${title}.mp3`;
        document.body.appendChild(a);
        a.click();
        URL.revokeObjectURL(blobUrl);
        document.body.removeChild(a);
      });
    };

    onMounted(async () => {
      await initList();
      queryList();
    });

    return {
      desc,
      instrumental,
      model,
      isLoading,
      genStates,
      audioSource,
      audioLyrics,
      playingIndex,
      list,
      listInfo,
      fallbackCover,
      clearList,
      handleGenerate,
      selectSong,
      downloadSong,
    };
  },
};
</script>
  
  <style scoped>
  .container {
    display: flex; 
    min-height: 100vh; 
    background: linear-gradient(180deg, rgba(30, 30, 64, 1) 0%, rgba(32, 32, 50, 1) 100%);
  }
  
  .content {
    flex: 1; /* 自动填充剩余空间 */
    overflow-y: auto; /* 允许垂直滚动 */
  }


.compositon_content{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: start;
  align-items: start;
}

.compositon_left{
  width: 450px;
  height: 100%;
  border-right: 1px solid #393a4a;
  overflow-y: scroll;
  font-size: 16px;
  padding-right: 10px;
  padding-bottom: 30px;
  box-sizing: border-box;

}

.comp_type{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.comp_type_button {
  width: 198px;
  height: 42px;
  border: 1px solid #414162;
  border-radius: 5px;
  display: flex;
  flex-direction: row;
  justify-content: start;
}

.comp_type_button button {
  width: 50%;
  height: 100%;
  color: #FFF;
  font-size: 18px;
  border-radius: 5px;
}

.comp_type_button button.active {
  background-color: #FFF;
  color: #515a63;
}


/* 歌曲描述 */
.music_keyword{
    margin-top: 20px;
}
.textarea_con{
  width: 100%;
  height: 170px;
  background: linear-gradient(180deg, rgba(41, 41, 64, 1) 0%, rgba(71, 73, 83, 1) 100%);
  border-radius: 5px;
  border-top: 1px solid rgba(71, 73, 83, 1);
  overflow: hidden;
  margin-top: 10px;
}

.textarea_con textarea {
  width: 100%;
  height: 120px;
  border: none;
  padding: 5px;
  box-sizing: border-box;
  background: none;
  color:#FFF;
  font-size: 14px;
}

.prompt{
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.prompt button {
  width: 100px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background-color: #a8a9b4;
  color: #515a63;
  border-radius: 5px;
  font-size: 16px;
  margin-left: 10px;
}

.prompt p {
  color: #bcc9de;
  font-size: 16px;
  margin-right: 10px;
}

.music_type {
  margin-top: 20px;
}

.button_row {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.music_type_btn button{
  width: 86px;
  height: 42px;
  border-radius: 5px;
  margin-right: 10px;
  text-align: left;
  background:#FFF url(../images/icon_musicType_link.png) no-repeat 10px center;
  overflow: hidden;
  color: #515a63;
}

.music_type_btn button div {
  width: 100%;
  height: 100%;
  line-height: 42px;
  font-size: 16px;
  padding-left: 36px;
  box-sizing: border-box;
}

.music_type_btn button.active {
  background: linear-gradient(180deg, rgba(163, 253, 248, 1) 0%, rgba(191, 160, 254, 1) 100%);
}
.music_type_btn button.active div {
  background: url(../images/icon_musicType_active.png) no-repeat 4px center;
}

.tab_swtich_con {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.tab_swtich_con p{
  font-size: 18px;
  color: #FFF;
  margin-right: 20px;
}

.tab_swtich{
  width: 50px;
  height: 31px;
  background-color: #CCC;
  padding:2px;
  box-sizing: border-box;
  border-radius: 50px;
  transition: all .3s;
}
.slide_btn {
  background: #fff;
  border-radius: 100px;
  width: 27px;
  height: 27px;
  box-shadow: 0px 3px 1px 0px rgba(0, 0, 0, 0.06), 0px 3px 8px 0px rgba(0, 0, 0, 0.15), 0px 0px 0px 1px rgba(0, 0, 0, 0.04);
  cursor: pointer;
  transition: all .3s;
}

.tab_swtich.active {
  background-color: #bbaefd;
}

.tab_swtich.active .slide_btn {
  margin-left: 19px;
}

.music_type_detail{
  width: 100%;
  height: 190px;
  margin-top: 20px;
}

.music_type_detail ul{
  
  display: flex;
  flex-wrap: wrap; /* 允许子元素自动换行 */
  gap: 10px; /* 设置元素之间的间隔 */
}

.music_type_detail ul li {
  width: 79px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  color: #75767b;
  border: 1px solid #75767b;
  border-radius: 5px;
  box-sizing: border-box;
  cursor: pointer;
  overflow: hidden;
}

.music_type_detail ul li.active {
  background: linear-gradient(180deg, rgba(164, 252, 249, 1) 0%, rgba(190, 165, 254, 1) 100%);
  padding: 1px;
  box-sizing: border-box;
  color: #FFF;
  border: none;
  border-radius: 5px;
}
.music_type_detail ul li.active div {
  height: 38px;
  background-color: #3e3e61;
  border-radius: 5px;
}



.music_model {

}

.model_btn {
  margin-top: 10px;
  width: 100%;
  height: 50px;
  background: rgba(255, 255, 255, 0.07);
  border-radius: 6px;
  border: 1px solid rgba(255, 255, 255, .38);
  /* box-shadow: -2px 3px 4.3px 0px rgba(210, 220, 237, 1); */
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  color: #FFF;
}


.lyrics_container {
  margin-top: 20px;
}

.lyrics_textarea {
  width: 100%;
  height: 230px;
  margin-top: 10px;
  border-radius: 5px;
  padding: 10px;
  box-sizing: border-box;
  background: linear-gradient(180deg, rgba(43, 43, 65, 1) 0%, rgba(70, 72, 82, 1) 100%);
}

.lyrics_textarea textarea {
  width: 100%;
  height: 164px;
  background:none;
  border: 0;
  color: #FFF;
  
}

.lyrice_btn {
  
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.lyrice_btn button {
  width: 109px;
  height: 42px;
  line-height: 42px;
  text-align: center;
  font-size: 16px;
  background: #a8a9b4;
  border-radius: 6px;
}

.lyrice_btn p {
  color:#bcc9de;
}

.reset_submit {
  display: flex;
  flex-direction: row;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.reset_submit button {
  width: 188px;
  height: 42px;
  line-height: 42px;
  border-radius: 5px;
  font-size: 16px;
  color: #FFF;
  text-align: left;
  padding-left: 70px;
  box-sizing: border-box;
}

.reset_submit button:nth-child(1) {
  background: #E13F79 url(../images/icon_reset.png) no-repeat 64% center;
}

.reset_submit button:nth-child(2) {
  background: #E13F79 url(../images/icon_music.png) no-repeat 64% center;
}



.compositon_right{
  height: 100%;
  flex: 1;
  overflow-y: scroll;
  padding-left: 30px;
  box-sizing: border-box;
}

.work_list {
  margin-bottom: 20px;
}

.title {
  font-size: 24px;
  color: #FFF;
} 

  </style>
  